using System.Collections.Generic;
using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using 第六次作业.entity;
using 第六次作业.utils.crud;

namespace 第六次作业;

public partial class MainWindow : Window
{
    private readonly SchoolRepository _schoolRepository;
    private readonly ClassRepository _classRepository;
    private readonly StudentRepository _studentRepository;
    private readonly LogRepository _logRepository;

    private ListBox _schoolListBox;
    private ListBox _logBox;
    private ListBox _classListBox;
    private ListBox _studentListBox;
    private TextBox _schoolNameTextBox;
    private TextBox _classNameTextBox;
    private TextBox _studentNameTextBox;
    private WindowNotificationManager? _notificationManage;

    private School? _selectedSchool;
    private Class? _selectedClass;

    public MainWindow()
    {
        _schoolRepository = new SchoolRepository();
        _classRepository = new ClassRepository();
        _studentRepository = new StudentRepository();
        _logRepository = new LogRepository();

        InitializeComponent();
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);

        _schoolListBox = this.FindControl<ListBox>("schoolListBox");
        _classListBox = this.FindControl<ListBox>("classListBox");
        _studentListBox = this.FindControl<ListBox>("studentListBox");
        _schoolNameTextBox = this.FindControl<TextBox>("schoolNameTextBox");
        _classNameTextBox = this.FindControl<TextBox>("classNameTextBox");
        _studentNameTextBox = this.FindControl<TextBox>("studentNameTextBox");
        _logBox = this.FindControl<ListBox>("logBox");
        
        ContextMenu schoolContextMenu = new ContextMenu();
        MenuItem deleteSchoolMenuItem = new MenuItem {Header = "Delete"};
        deleteSchoolMenuItem.Click += SchoolListBox_DeleteClick;
        schoolContextMenu.Items.Add(deleteSchoolMenuItem);
        
        ContextMenu classContextMenu = new ContextMenu();
        MenuItem deleteClassMenuItem = new MenuItem {Header = "Delete"};
        deleteClassMenuItem.Click += ClassListBox_DeleteClick;
        classContextMenu.Items.Add(deleteClassMenuItem);
        
        ContextMenu studentContextMenu = new ContextMenu();
        MenuItem deleteStudentMenuItem = new MenuItem {Header = "Delete"};
        deleteStudentMenuItem.Click += StudentListBox_DeleteClick;
        MenuItem editStudentMenuItem = new MenuItem {Header = "Update"};
        editStudentMenuItem.Click += StudentListBox_EditClick;
        studentContextMenu.Items.Add(editStudentMenuItem);
        studentContextMenu.Items.Add(deleteStudentMenuItem);
        
        
        _schoolListBox.ContextMenu = schoolContextMenu;
        _classListBox.ContextMenu = classContextMenu;
        _studentListBox.ContextMenu = studentContextMenu;

        LoadSchools();
    }

    private void LoadSchools()
    {
        var schools = _schoolRepository.GetAll();
        _schoolListBox.Items.Clear();
        foreach (var school in schools)
        {
            _schoolListBox.Items.Add("ID:" + school.Id + " " + "Name: " + school.Name);
        }
    }

    private void LoadClasses(int schoolId)
    {
        var classes = _classRepository.GetAll(schoolId);
        _classListBox.Items.Clear();
        foreach (var cls in classes)
        {
            _classListBox.Items.Add("ID:" + cls.Id + " " + "Class: " + cls.Name);
        }

    }

    private void LoadStudents(int classId)
    {
        var students = _studentRepository.GetAll(classId);
        _studentListBox.Items.Clear();
        foreach (var student in students)
        {
            _studentListBox.Items.Add("ID:" + student.Id + " " + "Name: " + student.Name);
        }
    }

    private void CreateSchoolButton_Click(object sender, RoutedEventArgs e)
    {
        // if (schoolNameTextBox.Text == "")
        // {
        //     WindowNotificationManager notificationManage = new WindowNotificationManager(this)
        //     {
        //         Position = NotificationPosition.TopLeft,
        //         MaxItems = 3
        //     };
        //     notificationManage.Show(new Notification("错误", "请输入学校", NotificationType.Error));
        //     return;
        // }
        var school = new School
        {
            Name = _schoolNameTextBox.Text
        };
        _schoolRepository.Create(school);
        LoadSchools();
        _logRepository.Create($"Created school '{school.Name}'");
    }

    private void CreateClassButton_Click(object sender, RoutedEventArgs e)
    {
        if (_selectedSchool == null)
        {
            _notificationManage = new WindowNotificationManager(this)
            {
                Position = NotificationPosition.TopLeft,
                MaxItems = 3
            };
            _notificationManage.Show(new Notification("错误", "请选择学校", NotificationType.Error));
            return;
        }
        Class cls = new Class
        {
            Name = _classNameTextBox.Text,
            SchoolId = _selectedSchool.Id
        };
        _classRepository.Create(cls);
        LoadClasses(_selectedSchool.Id);
        _logRepository.Create($"Created class '{cls.Name}' in school '{_selectedSchool.Name}'");
    }

    private void CreateStudentButton_Click(object sender, RoutedEventArgs e)
    {
        if (_selectedSchool == null)
        {
            _notificationManage = new WindowNotificationManager(this)
            {
                Position = NotificationPosition.TopLeft,
                MaxItems = 3
            };
            _notificationManage.Show(new Notification("错误", "请选择学校", NotificationType.Error));
            return;
        }
        else if (_selectedClass == null)
        {
            _notificationManage = new WindowNotificationManager(this)
            {
                Position = NotificationPosition.TopLeft,
                MaxItems = 3
            };
            _notificationManage.Show(new Notification("错误", "请选择班级", NotificationType.Error));
            return;
        }
        
        var student = new Student
        {
            Name = _studentNameTextBox.Text,
            ClassId = _selectedClass.Id
        };
        _studentRepository.Create(student);
        LoadStudents(_selectedClass.Id);
        _logRepository.Create($"Created student '{student.Name}' in class '{@_selectedClass.Name}'");
    }
    
    private void ShowLogButton_Clicked(object sender, RoutedEventArgs e)
    {
        var logs = _logRepository.GetAll();
        foreach (var log in logs)
        {
            _logBox.Items.Add(log.Id + ":" + log.Timestamp + " " + log.Action);
        }
    }

    private void SchoolListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        string? selectedItem = _schoolListBox.SelectedItem?.ToString();
        if (selectedItem == null)
        {
            return;
        }
        int id = int.Parse(selectedItem.Split(':')[1].Split(' ')[0]);
        _selectedSchool = _schoolRepository.GetById(id);
        if (_selectedSchool != null)
        {
            LoadClasses(_selectedSchool.Id);
        }
    }

    private void ClassListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        string? selectedItem = _classListBox.SelectedItem?.ToString();
        if (selectedItem == null)
        {
            return;
        }
        int id = int.Parse(selectedItem.Split(':')[1].Split(' ')[0]);
        _selectedClass = _classRepository.GetById(id);
        if (_selectedClass != null)
        {
            LoadStudents(_selectedClass.Id);
        }
    }
    
    public void SchoolListBox_DeleteClick(object sender, RoutedEventArgs e)
    {
        string? selectedItem = _schoolListBox.SelectedItem?.ToString();
        if (selectedItem == null)
        {
            return;
        }
        int id = int.Parse(selectedItem.Split(':')[1].Split(' ')[0]);
        _studentRepository.DeleteByClassId(id);
        _classRepository.DeleteBySchoolId(id);
        _schoolRepository.Delete(id);
        LoadSchools();
        _studentListBox.Items.Clear();
        _classListBox.Items.Clear();
        _logRepository.Create($"Deleted school '{selectedItem}'");
    }
    
    public void ClassListBox_DeleteClick(object sender, RoutedEventArgs e)
    {
        string? selectedItem = _classListBox.SelectedItem?.ToString();
        if (selectedItem == null)
        {
            return;
        }
        int id = int.Parse(selectedItem.Split(':')[1].Split(' ')[0]);
        _classRepository.Delete(id);
        _studentRepository.DeleteByClassId(id);
        LoadClasses(_selectedSchool.Id);
        _logRepository.Create($"Deleted class '{selectedItem}'");
    }
    
    public void StudentListBox_DeleteClick(object sender, RoutedEventArgs e)
    {
        string? selectedItem = _studentListBox.SelectedItem?.ToString();
        if (selectedItem == null)
        {
            return;
        }
        int id = int.Parse(selectedItem.Split(':')[1].Split(' ')[0]);
        _studentRepository.Delete(id);
        LoadStudents(_selectedClass.Id);
        _logRepository.Create($"Deleted student '{selectedItem}'");
    }

    public void StudentListBox_EditClick(object sender, RoutedEventArgs e)
    {
        string? selectedItem = _studentListBox.SelectedItem?.ToString();
        if (selectedItem == null)
        {
            return;
        }

        int id = int.Parse(selectedItem.Split(':')[1].Split(' ')[0]);
        var student = _studentRepository.GetById(id);
        if (student == null)
        {
            return;
        }

        LoadStudents(_selectedClass.Id);
        _logRepository.Create($"Edited student '{selectedItem}'");
    }
}
